package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.PurchaseService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneItemVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceiveList(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();

        // 查询状态是0和1的采购订单
        wrapper.eq("status", 0).or().eq("status", 1);

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        // 判断采购单ID若为空，则创建一个新的采购单
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();

            purchaseEntity.setPriority(100);
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());

            this.save(purchaseEntity);
            // 保存了新的采购单后，获取新的采购单ID
            purchaseId = purchaseEntity.getId();
        }
        //todo 当采购单为其他状态时，不允许合并

        Long finalPurchaseId = purchaseId;
        List<Long> items = mergeVo.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();

            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());

            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(purchaseDetailEntities);
    }

    @Override
    public void received(List<Long> purchaseIds) {
        // 更新采购单的状态
        List<PurchaseEntity> purchaseEntities = purchaseIds.stream().map(this::getById).filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
            item.setUpdateTime(new Date());

            return item;
        }).collect(Collectors.toList());

        this.updateBatchById(purchaseEntities);

        // 更新采购需求的状态
        purchaseEntities.forEach(purchaseEntity -> {
            Long purchaseId = purchaseEntity.getId();

            QueryWrapper<PurchaseDetailEntity> wrapper = new QueryWrapper<>();

            List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailService.list(wrapper.eq("purchase_id", purchaseId));
            List<PurchaseDetailEntity> list = purchaseDetailEntityList.stream().map(purchaseDetailEntity -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setId(purchaseDetailEntity.getId());
                entity.setStatus(WareConstant.PurchaseDetailStatusEnum.WORKING.getCode());

                return entity;
            }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(list);
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        // 1. 更新采购单状态，判断采购需求详情是否全部成功，若存在不成功的，则更新为有异常
        List<PurchaseDoneItemVo> items = purchaseDoneVo.getItems();
        boolean flag = true;

        List<PurchaseDetailEntity> purchaseDetailList = new ArrayList<>();
        for (PurchaseDoneItemVo purchaseDoneItemVo : items) {
            // 2. 更新采购需求的状态
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(purchaseDoneItemVo.getItemId());
            purchaseDetailEntity.setStatus(purchaseDoneItemVo.getStatus());

            purchaseDetailList.add(purchaseDetailEntity);

            if (purchaseDoneItemVo.getStatus() == WareConstant.PurchaseDetailStatusEnum.FINISHED.getCode()) {
                // 3. 若完成采购，更新库存信息
                PurchaseDetailEntity purchaseDetail = purchaseDetailService.getById(purchaseDoneItemVo.getItemId());

                wareSkuService.updateSkuNum(purchaseDetail.getWareId(), purchaseDetail.getSkuId(), purchaseDetail.getSkuNum());
            } else {
                flag = false;
            }
        }

        purchaseDetailService.updateBatchById(purchaseDetailList);

        // 判断所有的需求单是否都已采购成功
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVo.getId());
        purchaseEntity.setUpdateTime(new Date());
        if (flag) {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISHED.getCode());
        } else {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        }

        this.updateById(purchaseEntity);
    }

}